#!/bin/sh
#
# Starts gateway daemon
#

UPDATE_FILE="/tmp/gateway.update"
EXEC_FILE="/usr/bin/gateway"
OLD_EXEC_FILE="/usr/bin/gateway.old"
PID_FILE="/var/run/gateway.pid"
ERROR_FLAG="/tmp/gateway.error"

start() {
    #ROLLBACK
    if [ -f "$ERROR_FLAG" ]; then
        if [ -f "$OLD_EXEC_FILE" ]; then
            rm "$EXEC_FILE"
            mv "$OLD_EXEC_FILE" "$EXEC_FILE"
        fi
        rm "$UPDATE_FILE"
        rm "$ERROR_FLAG"
    #OTA
    elif [ -f "$UPDATE_FILE" ]; then
        chmod +x "$UPDATE_FILE"
        rm "$OLD_EXEC_FILE"
        mv "$EXEC_FILE" "$OLD_EXEC_FILE"
        mv "$UPDATE_FILE" "$EXEC_FILE"
    fi

    printf "Starting gateway: "
    umask 077

    start-stop-daemon -S -q -p $PID_FILE \
        --exec $EXEC_FILE -- daemon
    [ $? = 0 ] && echo "OK" || echo "FAIL"
}
stop() {
    printf "Stopping gateway: "
    start-stop-daemon -K -q -p $PID_FILE
    [ $? = 0 ] && echo "OK" || echo "FAIL"
}

case "$1" in
start)
    start
    ;;
stop)
    stop
    ;;
restart | reload)
    stop
    start
    ;;
*)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
    ;;
esac

exit $?
